package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.*;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.IZJYAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class ZJYAPIImpl implements IZJYAPI {
    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;

    @Override
    public AjaxResult addGame(AccountInfo accountInfo,Long userId, SalePartner salePartner) {
        Map<String, Object> params = params(accountInfo,salePartner);
        String path = "/tripartite/shopadd";
        //进行排序
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        Map<String, Object> map = getSignAndsortMap(entries,salePartner);

        log.info("指间游新增请求参数={}", JSONObject.toJSONString(map));
        String twoOther = salePartner.getTwoOther();
        String response =   HttpUtils.doPostForm(twoOther + path, map,null);

        log.info("指尖游返回{}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String info = resultJson.getString("info");

        Map<String, Object> result = new HashMap<>();
        if (!"100".equals(resultJson.getString("code"))) {
            result.put("code",500);
        }else {
            result.put("code",200);
        }
        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",info);
        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult editGame(AccountInfo accountInfo,Long userId, SalePartner salePartner) {
        Map<String, Object> params = params(accountInfo,salePartner);
        String path = "/tripartite/shopedit";
        String paramsStr = JSONObject.toJSONString(params);
        log.info("指间游编辑请求参数={}", paramsStr);
        //进行排序
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        Map<String, Object> map = getSignAndsortMap(entries,salePartner);
        String twoOther = salePartner.getTwoOther();
        String response =   HttpUtils.doPostForm(twoOther + path, map,null);

        log.info("{}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String info = resultJson.getString("info");

        Map<String, Object> result = new HashMap<>();
        if (!"100".equals(resultJson.getString("code"))) {
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",info);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(Long id,Long userId, SalePartner salePartner) {


        String path = "/tripartite/shopcontrol";
        HashMap<String, Object> params = new HashMap<>();
        params.put("shopcode", id.toString());
        params.put("type", Integer.valueOf(ZJYConstant.DEL.getValue()));
        params.put("importcode", salePartner.getOther());
        params.put("importid", salePartner.getThreeOther());
        String paramsStr = JSONObject.toJSONString(params);
        log.info("指间游删除请求参数={}", paramsStr);
        //进行排序
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        Map<String, Object> map = getSignAndsortMap(entries,salePartner);
        String twoOther = salePartner.getTwoOther();
        String response =   HttpUtils.doPostForm(twoOther + path, map,null);

        log.info("{}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String info = resultJson.getString("info");
        info = MapUntils.unicodeToString(info);

        Map<String, Object> result = new HashMap<>();
        if (!"100".equals(resultJson.getString("code"))) {
            result.put("code",500);
        }else {
            result.put("code",200);
        }

        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",info);
        return AjaxResult.success(result);
    }

    private Map<String, Object> params(AccountInfo accountInfo,SalePartner sa) {


        String des = accountInfo.getDes();

        des = des.replace("+"," ");
        des = des.replace("☝"," ");
        accountInfo.setDes(des);

        //填充参数
        Map<String, Object> params = new HashMap<>();
        //标题
        String title =  "【xyr|" + accountInfo.getId() + "】 " + accountInfo.getLevel() + "  " + accountInfo.getDes();
//        String title =  "1";
        //游戏分类ID，详情见附录
        Integer cateid = (Integer) RegionalCovert.getZjyGameTypeMap(accountInfo.getType());
        //游戏分类ID，详情见附录
        Integer cateid2 = (Integer) RegionalCovert.getZjyRegionIdMap(accountInfo.getType(), accountInfo.getRegional());
        if (StringUtils.isNull(cateid)) {
            throw new GlobalException("游戏类型未找到");
        }
        if (StringUtils.isNull(cateid2)) {
            throw new GlobalException("游戏大区未找到");
        }
        //游戏属性或关键字，英文逗号拼接，例如：至臻卡莎,至臻阿卡丽,至臻拉克丝
        String attribute = accountInfo.getDes();
        //商品编号
        String shopcode = accountInfo.getId().toString();
        Double money = accountInfo.getPrice().doubleValue();
        //详情说明，富文本或纯文字说明均可
        String text = "";
        String logo = accountInfo.getTitleImg();


        //图片
        StringBuilder imagesSb = new StringBuilder();
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
            params.put("images", sa.getTwoOther());
        } else {
            for (InfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
            String images = imagesSb.toString();
            params.put("images", images);
        }

        params.put("title", title);
        params.put("cateid", cateid);
        params.put("cateid2", cateid2);
        params.put("attribute", attribute);
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);
        params.put("money", bigDecimal);
        params.put("shopcode", shopcode);
        params.put("text", text);
        params.put("logo", logo);
        params.put("importcode", sa.getOther());
        params.put("importid", sa.getThreeOther());
        return params;
    }

    private Map<String, Object> getSignAndsortMap(List<Map.Entry<String, Object>> entries,SalePartner sa) {


        String key = sa.getSaleKey();
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
        sb.append("key=" + key);
        String sign = DigestUtils.md5Hex(sb.toString());
        Map<String, Object> map = MapSort.sortMapByKey(newMap);
        map.put("sign", sign);
        return map;
    }

    public static void main(String[] args) {

        String key = "weacb2c7cfcxd5c31a";
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        Map<String,Object> params = new HashMap<>();

        params.put("cate_id","12");
        params.put("name","1");
        params.put("image","12");
        params.put("arealist","1");

        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
        sb.append("key=" + key);
        String sign = DigestUtils.md5Hex(sb.toString());
        Map<String, Object> map = MapSort.sortMapByKey(newMap);
        map.put("sign", sign);

//        https://www.zhijianyo.com/gshop/tripartite/catelist
        String path = "https://www.milaiyou.com/qyshop/tripartite/catelist";

        String response =   HttpUtils.doPostForm( path, map,null);
        System.out.println(response);

    }
}
